package com.igeek.compus.backend.system.utils;

import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;

@Component
public class JedisUtil {

    @Resource
    private JedisPool jedisPool;

    /**
     * 获得jedis对象
     * @return
     */
    public Jedis getResource() {
        return jedisPool.getResource();
    }

    /**
     * 销毁jedis连接对象
     * @param jedis
     */
    public void returnResource(Jedis jedis) {
        jedisPool.returnResource(jedis);
    }

    /**
     * 获得string类型
     * @param key
     * @return
     */
    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        }finally {
            this.jedisPool.returnResource(jedis);
        }
    }

    /**
     * 设置string value
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        }finally {
            this.jedisPool.returnResource(jedis);
        }
    }

    public void setex(String key, long seconds, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.setex(key, seconds, value);
        }finally {
            this.jedisPool.returnResource(jedis);
        }
    }
}
